package com.tezign.intelligence.mini.dam.aifamilyconsultant.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.List;

public class DeepSeekUtil {

    private static WebClient webClient;
//    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";
    private static final String DEEPSEEK_API_URL = "https://api.302.ai/v1/chat/completions";
//    private static final String API_KEY = "sk-ff75e8fd8bbd49c59a05872476cc5864"; // 替换为你的实际API密钥
    private static final String API_KEY = "sk-DxuqVi2JpSQ7brhuDL4bD7KSvoYT89D9FJkHdJSl3a3w9FpL"; // 替换为你的实际API密钥

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static Flux<String> streamChat(List<ChatMessage> messages) {
//        webClient = WebClient.Builder.baseUrl(DEEPSEEK_API_URL).build();
        WebClient client = WebClient.create(DEEPSEEK_API_URL);
        // 构建DeepSeek API请求deepseek-chat
        DeepSeekRequest request = new DeepSeekRequest(
                "deepseek-v3.1-huoshan", // 模型名称，根据DeepSeek API文档调整
                messages,
                true, // 启用流式响应
                0.7 // 温度参数
        );

        // 调用DeepSeek API并处理流式响应
        return client.post()
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .header("Accept", "text/event-stream")
                .bodyValue(request)
                .retrieve()
                .bodyToFlux(String.class);
    }

    // 解析DeepSeek API返回的chunk数据
    public static String parseChunk(String chunk) {
        // 这里需要根据DeepSeek API实际的流式响应格式进行解析
        // 示例实现，实际需要调整
        try {
            JsonNode node = new ObjectMapper().readTree(chunk);
            if (node.has("choices") && node.get("choices").size() > 0) {
                JsonNode choice = node.get("choices").get(0);
                if (choice.has("delta") && choice.get("delta").has("content")) {
                    return choice.get("delta").get("content").asText();
                }
            }
        } catch (Exception e) {
            return "";
        }
        return "";
    }

    // 内部类定义请求和消息结构
    @Data
    @AllArgsConstructor
    private static class DeepSeekRequest {
        private String model;
        private List<ChatMessage> messages;
        private boolean stream;
        private double temperature;
    }

}